package com.stylefeng.guns.core.util;

import java.io.File;
import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.w3c.dom.Document;
/**
 * 编号生成器
 * @author Administrator
 *
 */
public class NoGenerateUtils {
	
	private static AtomicLong atomic = new AtomicLong(1);
	
	/**
	 * 获取编号 ： 20170319121300 + 00001
	 * @return
	 */
	public static String getTimeNo(){
		
		if (atomic.get() > 9999999) {
			atomic.set(1);
		}
		
		String nowTime = DateFormatUtils.format(new Date(), "yyyyMMddHHmmss");
		long no =  atomic.getAndIncrement();
		
		if (no < 10 ) {
			nowTime = nowTime + "00000" + no; 
		} else if(no < 100){
			nowTime = nowTime + "0000" + no; 
		}else if(no < 1000){
			nowTime = nowTime + "000" + no; 
		}else if(no < 1000){
			nowTime = nowTime + "000" + no; 
		}else if(no < 10000){
			nowTime = nowTime + "00" + no; 
		}else if(no < 10000){
			nowTime = nowTime + "0" + no; 
		}else {
			nowTime = nowTime + no; 
		}
		
		return nowTime;
	}
	
	/**
	 * 获取编号 ： E000001
	 * @return
	 */
	public static String getNo(){
		
		if (atomic.get() > 999999) {
			atomic.set(1);
		}
		
		String nowTime ="E";
		long no =  atomic.getAndIncrement();
		
		
		if (no < 10 ) {
			nowTime = nowTime + "000000" + no; 
		} else if(no < 100){
			nowTime = nowTime + "00000" + no; 
		}else if(no < 1000){
			nowTime = nowTime + "0000" + no; 
		}else if(no < 1000){
			nowTime = nowTime + "0000" + no; 
		}else if(no < 10000){
			nowTime = nowTime + "000" + no; 
		}else if(no < 100000){
			nowTime = nowTime + "00" + no; 
		}else if(no < 1000000){
			nowTime = nowTime + "0" + no; 
		}else {
			nowTime = nowTime + no; 
		}
		
		return nowTime;
	}
	
	public static Integer getTomcatPortFromConfigXml(File serverXml) {
		   Integer port;
		   try {
		      DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
		      domFactory.setNamespaceAware(true); // never forget this!
		      DocumentBuilder builder = domFactory.newDocumentBuilder();
		      Document doc = builder.parse(serverXml);
		      XPathFactory factory = XPathFactory.newInstance();
		      XPath xpath = factory.newXPath();
		      XPathExpression expr = xpath.compile("/Server/Service[@name='Catalina']/Connector[count(@scheme)=0]/@port[1]");
		      String result = (String) expr.evaluate(doc, XPathConstants.STRING);
		      port =  result != null && result.length() > 0 ? Integer.valueOf(result) : null;
		   } catch (Exception e) {
		     port = null;
		   }
		   return port;
		}
	
	public static void main(String[] args) {
		
		File file = new File("D:\\developsoft\\apache-tomcat-8.0.35-sns\\conf\\server.xml");
		System.out.println(getTomcatPortFromConfigXml(file));
		
	}

}
